package org.streets.eis.component.model;

import java.io.Serializable;
import java.util.List;

import org.apache.wicket.model.IModel;

import com.inmethod.grid.IDataSource;
import com.inmethod.grid.IGridSortState;
import com.inmethod.grid.IGridSortState.ISortStateColumn;

public abstract class LoadableTableModel<T extends Serializable> implements IDataSource {
	private static final long serialVersionUID = 1L;

	public LoadableTableModel() {		
	}

	
	@SuppressWarnings("unchecked")
	public IModel model(Object object) {
		return new LoadableRowModel<T>((T)object){
			private static final long serialVersionUID = 1L;

			@Override
			protected T load() {
				return LoadableTableModel.this.loadRowObject(getId());
			}
			
		};
	}
	
	public void query(IQuery query, IQueryResult result) {
		String sortProperty = null;
		boolean isAsc = true;

		if (query.getSortState().getColumns().size() > 0) { 
			ISortStateColumn state = query.getSortState().getColumns().get(0);
			sortProperty = state.getPropertyName();
			isAsc = state.getDirection() == IGridSortState.Direction.ASC;
		}
		
		result.setTotalCount(IDataSource.IQuery.UNKNOWN_TOTAL_COUNT);
		
		List<T> resultList = getPageRecords(query.getFrom(),query.getCount(),sortProperty,isAsc);
		result.setItems(resultList.iterator());
		
		long count = getRecordsCount();
		result.setTotalCount(Long.valueOf(count).intValue());		
	}

	public void detach() {
	}
	
	public abstract List<T> getPageRecords(long offset,int limit,String sortProperty,boolean isAsc);
	
	protected abstract long getRecordsCount();
	
	public abstract T loadRowObject(String id);
}
